package com.example.controller;

import com.example.common.constant.JwtClaimsConstant;
import com.example.common.context.BaseContext;
import com.example.common.properties.JwtProperties;
import com.example.common.result.Result;
import com.example.common.utils.JwtUtil;
import com.example.entity.User;
import com.example.entity.dto.ProjectDto;
import com.example.entity.dto.UserDto;
import com.example.entity.vo.UserVo;
import com.example.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/applet")
@Api(tags = "用户相关接口")
@Slf4j
public class UserController {

    @Autowired
    private LoginService loginService;

	@Autowired
	private JwtProperties jwtProperties;


	/**
	 * 登录
	 * @param userDto
	 * @return
	 */
	@PostMapping("/login")
	@ApiOperation("登录")
	public Result<UserVo> loginUser(@RequestBody UserDto userDto) {
		log.info("用户登录：{}",userDto);
		//登录成功后，生成jwt令牌
		User user = loginService.loginUser(userDto);;
		Map<String, Object> claims = new HashMap<>();
		claims.put(JwtClaimsConstant.EMP_ID, user.getId());
		String token = JwtUtil.createJWT(
				jwtProperties.getAdminSecretKey(),
				jwtProperties.getAdminTtl(),
				claims);
		UserVo userVo = new UserVo();
		userVo.setToken(token);
		BaseContext.setCurrentId(user.getId());
		BeanUtils.copyProperties(user,userVo);
		return Result.success(userVo);
	}

	/**
	 * 用户重置密码
	 * @param userDto
	 * @return
	 */
	@PostMapping("/reset")
	@ApiOperation("重置密码")
	public Result resetUser(@RequestBody UserDto userDto){
		log.info("用户重置密码：{}",userDto);
		loginService.resetPassword(userDto);

		return Result.success();
	}
	/**
	 * 用户修改密码
	 * @param userDto
	 * @return
	 */
	@PostMapping("/change")
	@ApiOperation("修改密码")
	public Result changeUser(@RequestBody UserDto userDto,String password){
		log.info("用户修改密码：{}",userDto);
		loginService.changePassword(userDto,password);
		return Result.success();
	}


}
